package net.xi.dmhome.controller;

import net.xi.dmhome.entity.Comment;
import net.xi.dmhome.handler.Result;
import net.xi.dmhome.mapper.CommentMapper;
import net.xi.dmhome.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Author: jxhu
 * @Description:
 * @Date Created in 2021-02-25 11:32
 * @Modified By:
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    CommentService commentService;
    /* @Description: 添加评论,@Param:  */
    @PostMapping("/add")
    public Result addComment(@Validated @RequestBody(required = false) Comment comment) throws Exception {
        if (comment.getParentid()!=null){
            String rely = "回复用户 " + comment.getParentuser()+" : " + comment.getContent();
            comment.setContent(rely);
        }
        int insert = commentMapper.insert(comment);
        if (insert != 0) {

            System.out.println("添加成功");
            return Result.success(200, "success", insert);
        } else {
            return Result.fail("添加失败");
        }
    }
    /* @Description: 根据帖子id查找对应的评论,@Param:  */
    @GetMapping("/findcommentbyid/{postid}")
    public Result getCommentById(@PathVariable("postid") Integer postid) throws Exception {
        List<Comment> comments =  commentMapper.getByPostidAfter(postid);
        return Result.success(comments);

    }
    /* @Description: 编辑评论,@Param:  */
    @PutMapping("/editComment")
    public Result editComment(@Validated @RequestBody Comment comment) throws Exception {
        boolean update = commentService.saveOrUpdate(comment);
        if (update !=false) {

            System.out.println("更改成功");
            return Result.success(200, "success", comment);
        } else {
            return Result.fail("更改失败");
        }
    }

    /* @Description: 删除评论,@Param:  */
    @DeleteMapping("/deleteComment/{id}")
    public Result deleteComment(@PathVariable("id") Integer id){
        int i = commentMapper.deleteById(id);
        if (i == 1){
            return Result.success("success");
        }else {
            return Result.fail("删除失败");
        }
    }

    /* @Description: 根据用户名查找对应的评论,@Param:  */
    @GetMapping("/findcommentbyuserUuid/{uuid}")
    public Result getCommentByUserUuid(@PathVariable("uuid") String uuid){

        List<Comment> comments =  commentMapper.getByUserUuid(uuid);
        return Result.success(comments);

    }
}
